package com.econage.eccm.test.base.webdatasource.web;

import com.econage.eccm.test.base.mybatis.support.MybatisWebContext;

import java.sql.Connection;
import java.util.concurrent.Callable;

public abstract class DbWorkWithAutoConnection<V> implements Callable<V> {


    @Override
    public V call() throws Exception {
        //当前处于web容器中，则不再做任何线程管理工作
        long dbActionId = 0;
        try {
            if(DbTransaction.getDbActionUid()==0){
                dbActionId = DbTransaction.register4Access();
            }
            return doAction();
        }catch(Throwable t){
            return handleException(t);
        }finally{
            if(dbActionId!=0){
                try{ MybatisWebContext.close();  }catch(Exception ignore){}
                try{ DbTransaction.closeForce(dbActionId); }catch(Exception ignore){}
            }
        }
    }

    //handleException决定怎么处理异常，可以重新抛出异常，也可以在异常出现后返回一个默认值
    protected V handleException(Throwable t) throws Exception {
        DbTransaction.rollback();
        throw new Exception(t);
    }

    protected Connection getConnection() {
        return DbTransaction.fetchConnection();
    }

    protected abstract V doAction() throws Exception;
}
